package com.sq.gateway.auth;

import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.core.util.StrUtil;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.sq.gateway.entity.AuthPermission;
import com.sq.gateway.entity.AuthRole;
import com.sq.gateway.redis.RedisUtil;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

@Component
public class StpInterfaceImpl implements StpInterface {

    @Resource
    private RedisUtil redisUtil;

    private String authRolePrefix = "auth.role";
    private String authPermissionPrefix = "auth.permission";

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        // 返回此 loginId 拥有的权限列表
        // 1、直接跟数据库交互
        // 2、redis缓存
        // 3、redis缓存，没有的话，去调用我们的微服务去获取
        return getAuth(loginId.toString(), authPermissionPrefix);
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        return getAuth(loginId.toString(), authRolePrefix);
    }

    private List<String> getAuth(String loginId, String prefix) {
        String authKey = redisUtil.buildKey(prefix,loginId);
        String authValue = redisUtil.get(authKey);
        if(StrUtil.isBlank(authValue)){
            return Collections.emptyList();
        }
        List<String> authList = new ArrayList<>();
        if(authRolePrefix.equals(prefix)){
            List<AuthRole> roleList = new Gson().fromJson(authValue, new TypeToken<List<AuthRole>>() {
            }.getType());
            authList = roleList.stream().map(AuthRole::getRoleKey).toList();
        }else if(authPermissionPrefix.equals(prefix)){
            List<AuthPermission> roleList = new Gson().fromJson(authValue, new TypeToken<List<AuthPermission>>() {
            }.getType());
            authList = roleList.stream().map(AuthPermission::getPermissionKey).toList();
        }
        return authList;
    }

}
